package com.nacrtstudio.webgiftshop.pages;

import java.util.HashSet;
import java.util.Set;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.nacrtstudio.webgiftshop.facade.Controller;
import com.nacrtstudio.webgiftshop.model.shop.CartItem;
import com.nacrtstudio.webgiftshop.model.shop.Gift;
import com.nacrtstudio.webgiftshop.model.shop.Order;
import com.nacrtstudio.webgiftshop.model.shop.PackedGift;

public class ShoppingCart {
	@Inject
	private Request request;
	public void onActivate() {
		try {
			if (controller.getRequest()==null) {
	    		controller.setRequest(request);
			}
		} catch (Exception e) {
		}
	}

	@Inject
	private Controller controller;
	@Property
	private Gift gift;
	@Property
	private CartItem cartItem;
	
	public Set<CartItem> getChosenGifts(){
		try {
			if (controller.getLoggedSignal()) {
				return controller.getLoggedUser().getCart().getCartItems();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	public void onActionFromDeleteItem(Long id){
		CartItem cartItem  = controller.findCartItem(id);
		controller.deleteItemFromShoppingCart(cartItem);
	}
	
	public void onActionFromDropShoopingCard(){
		try {
			controller.deleteShoopingCardFromLoggedUser();
		} catch (Exception e) {
		}
	}
	
	public int getItemNumber(CartItem cartItem){
		int result = 1;
		   for (CartItem g:getChosenGifts()) {
		     if (g.equals(cartItem)) return result;
		     result++;
		   }
		   return 1;
	}
	
	
	@InjectPage
	private OrderPage orderPage;
	public Object onActionFromCheckout(){
		if (controller.getLoggedUser().getCart().getCartItems().size()>0) {
			try {
//				orderPage.setOrder((Order) controller.packGifts());
//				return orderPage;
				return CustomerDetails.class;
			} catch (Exception e) {
				System.out.println("\n\n\n"+e);
			}
		}
		return null;
	}
	
	public void onActionFromAddMore(Long id){
		controller.addMore(id);
	}
	
	@InjectPage
	private GiftInfo giftInfo;
	Object onActionFromShow(Long id){
		giftInfo.setGift(controller.findGift(id));
    	return giftInfo;
    }
	
	public double getCena(double jeCena, int qty){
		return jeCena*qty;
	}
	public Double getTotalPrice(){
		Double total = new Double(0);
		try {
			for (CartItem cartItem : getChosenGifts()) {
				total = total+(cartItem.getGift().getPrice()*cartItem.getQty());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return total;
	}
}